// pages/comment/comment.js
const db = wx.cloud.database();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: "",
    comments: [],
    eventChannel: null,
    comment: "",
    fileList: [],
    user:{}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const eventChannel = this.getOpenerEventChannel();
    if (!eventChannel) {
      wx.navigateTo({
        url: '/miniprogram/pages/detail/detail',
      });
      return;
    }
    eventChannel.on('sendComments', (data) => {
      console.log(data);
      let {
        id,
        comments
      } = data;
      this.setData({
        id,
        comments,
        eventChannel
      });
      console.log(this.data.comments, 'comments');
    })
  },
  //更新comment
  changeComment(event) {
    let {
      value: comment
    } = event.detail;
    this.setData({
      comment
    });
  },
  //删除文件
  deleteFile(event) {
    console.log(event.detail.index, '111');
    let index = event.detail.index;
    this.setData({
      fileList: this.data.fileList.filter((el, i) => i != index)
    });
  },
  //上传文件
  afterRead(event) {
    const {
      file
    } = event.detail;
    console.log(file, 'file');
    const {
      fileList = []
    } = this.data;
    fileList.push({
      ...file
    });
    this.setData({
      fileList
    });
  },
  //发表评论
  uploadComment() {
    if (!this.data.comment) {
      wx.showToast({
        title: '评论内容不能为空',
        icon: 'none'
      });
      console.log(this.data.comment);
      return;
    };
    this.uploadToCloud();
  },
  //发表评论
  updateComments(newFileList=[]){
    let comment = {
      actionId: "0",
      avatar: this.data.user.img,
      comment: this.data.comment,
      commentId: `${Date.now()}${Math.floor(Math.random()*1000)}`,
      grade: 5,
      isDeleted: 0,
      isPraise: 0,
      isTop: 0,
      likes: 0,
      masterLevel: "0",
      nickName: this.data.user.name,
      replyCount: 0,
      select: "",
      self: 0,
      time: Date.now(),
      toSelf: 0,
      userAttr: 0,
      userId: this.data.user._id,
      userLevel: "14",
      imgList:newFileList
    };
    this.setData({
      fileList: newFileList,
      comments: [comment, ...this.data.comments]
    });
    wx.cloud.callFunction({
      name: "addComments",
      data: {
        id: this.data.id,
        type: "update",
        comments: comment
      }
    }).then(()=>{
      this.data.eventChannel.emit("sendComments",{comments:this.data.comments});
      wx.hideLoading();
      wx.navigateBack();
    });
  },
  // 上传图片
  uploadToCloud() {
    wx.showLoading({
      title: '加载中',
    });
    wx.cloud.init();
    const {
      fileList
    } = this.data;
    if (!fileList.length) {
      this.updateComments();
    } else {
      const uploadTasks = fileList.map((file, index) => this.uploadFilePromise(`comments/${Date.now()}${Math.floor(Math.random()*1000)}${index}.png`, file));
      Promise.all(uploadTasks)
        .then(data => {
          wx.showToast({
            title: '上传成功',
            icon: 'none'
          });
          const newFileList = data.map(item => ({
            url: item.fileID
          }));
          console.log(newFileList);
          this.updateComments(newFileList);
        })
        .catch(e => {
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          });
          console.log(e);
        });
    }
  },

  uploadFilePromise(fileName, chooseResult) {
    console.log(fileName, "fileName");
    return wx.cloud.uploadFile({
      cloudPath: fileName,
      filePath: chooseResult.url
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let user = wx.getStorageSync('user');
    if (!user?.usercode) {
      wx.navigateTo({
        url: '/pages/login/login',
      });
      return;
    };
    db.collection("user").where({
      _id:user._id
    }).get().then(res=>{
      user = res.data[0];
      this.setData({
        user
      });
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})